package net.onceface.core.domain.mappedsuper;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import net.onceface.core.domain.enums.NumberType;
import net.onceface.infra.domain.AbstractEntity;

/**
 * 编号生成
 * **/
@Entity
@Table(name = "SYS_NUMBER")
public class CreateNumber extends AbstractEntity{

	/**
	 * 
	 */
	private static final long serialVersionUID = -4764244167545276976L;
	
	/**
	 * 生成编号的类型
	 * **/
	@Enumerated(EnumType.STRING)
	@Column(name = "NUMBER_TYPE", nullable = false, unique = true)
	private NumberType numberType;
	
	/**
	 * 编号前缀
	 * **/
	@Column(name = "PREFIX")
	private String prefix;
	
	/**
	 * 编号后缀
	 * **/
	@Column(name = "NUMBER")
	private Long number;
	
	/**
	 * 创建日期
	 * **/
	@Column(name = "CREATE_DATE", nullable = false ,updatable = false)
	@Temporal(TemporalType.TIMESTAMP)
	private Date createDate;

	/**
	 * 根据类型生成编号
	 * **/
	public static String createNumber(NumberType numberType){
		CreateNumber number = getRepository().createJpqlQuery("SELECT _number FROM CreateNumber _number WHERE _number.numberType = :numberType")
				.addParameter("numberType", numberType)
				.singleResult();
		number.setNumber(number.getNumber() + 1);
		number.save();
		return number.getPrefix() + number.getNumber();
	}
	
	public NumberType getNumberType() {
		return numberType;
	}

	public void setNumberType(NumberType numberType) {
		this.numberType = numberType;
	}

	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public Long getNumber() {
		return number;
	}

	public void setNumber(Long number) {
		this.number = number;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	@Override
	public String[] businessKeys() {
		// TODO Auto-generated method stub
		return null;
	}

}
